﻿using System;
using System.Text;
using System.Web;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace CaptchaControl
{
    class CaptchaImageHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            // On the basis of the query string return get the
            // captcha image from the cache
            string guid = context.Request.QueryString["guid"];
            CaptchaImage captchaIamge = CaptchaImage.GetCachedCaptcha(guid);

            // If it is not available in the cache then return none
            if (String.IsNullOrEmpty(guid) || captchaIamge == null)
            {
                context.Response.StatusCode = 404;
                context.Response.StatusDescription = "Not Found";
                context.ApplicationInstance.CompleteRequest();
                return;
            }

            // Else return back the image by saving it into the 
            // output stream
            Bitmap b = captchaIamge.GenerateCaptcha();
            b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            
            // Set the type of response
            context.Response.ContentType = "image/jpg";
            context.Response.StatusCode = 200;
            context.Response.StatusDescription = "OK";
            context.ApplicationInstance.CompleteRequest();
        }

        #endregion
    }
}
